package realms;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.ibatis.session.SqlSession;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import dao.UserDao;
import entity.User;
import entity.UserRolePermisson;


/**
 * 自定义认证方式 Realm
 * 
 * @author Saltfish
 *
 */
public class UserRealms extends AuthorizingRealm {
	@Autowired
	private UserDao dao;
	
	/**
	 * 授权方法
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		
		
		System.out.println("授权方法被调用···");
		//查询subject的角色与权限
		String username=(String)principals.getPrimaryPrincipal();
		//查询数据库,得到list集合，角色数据，权限数据都在集合中
		List<UserRolePermisson> list=dao.findUserRolePermisson(username);
		
		//角色集合
		Set<String> rolesSet=new HashSet<String>();
		//权限集合
		Set<String> permissonsSet=new HashSet<String>();
		
		
		//取得角色数据，并分别装入角色集合与权限集合
		for(UserRolePermisson urp:list) {
			String rol=urp.getRname();
			String permisson=urp.getPname();
			//一边循环mybatis查询出来的数据一边加到集合
			rolesSet.add(rol);
			permissonsSet.add(permisson);
		}
		//创建返回数据
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		//将角色，权限添加到返回数据，返回给shiro进行比对
		info.addRoles(rolesSet);
		info.addStringPermissions(permissonsSet);
		return info;
	}

	/**
	 * 认证方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		System.out.println("自定义realm认证放法被调用");
		// 得到username
		String username = (String) token.getPrincipal();
		// 根据username从数据库去查询username对应的password

		User u = new User();
		u.setName(username);

		User user = dao.findUser(u);

		String password = user.getPassword();
		// 将查询搭配的结果和username进行包装并返回

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
		System.out.println(getName());
		return info;
	}

}
